package top.fangw.common.core.service;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import top.fangw.common.core.annotation.TrimString;
import top.fangw.common.core.enums.TrimType;
import top.fangw.common.core.util.StringUtil;

import java.lang.reflect.Field;


/**
 * @description: 用于去除字符串前后空格的切面
 * @author: fgw
 * @createDate: 2024/4/26
 */
@Aspect
@Component
public class TrimStringAspect {
    @Around("@annotation(trimString)")
    public Object around(ProceedingJoinPoint joinPoint, TrimString trimString) throws Throwable {
        Object[] args = joinPoint.getArgs();
        if(args ==null || args.length == 0){
            return joinPoint.proceed(args);
        }
        for (int i = 0; i < args.length; i++) {
            if (args[i] instanceof String) {
                args[i] = ((String) args[i]).trim();
            } else if (args[i] instanceof Object) {
                Object dto = (Object) args[i];
                Field[] fields = dto.getClass().getDeclaredFields();
                for (Field field : fields) {
                    if (field.getType().equals(String.class)) {
                        field.setAccessible(true);
                        String value = (String) field.get(dto);
                        if (value != null) {
                            if(trimString.value() == TrimType.ALL){
                                value = StringUtil.trimAll(value);
                            } else if(trimString.value() == TrimType.TRIM){
                                value = value.trim();
                            } else {
                                value = StringUtil.trimAll(value);
                            }

                            field.set(dto, value);
                        }
                    }
                }
            }
        }
        return joinPoint.proceed(args);
    }
}
